#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
import json
from datetime import datetime

def parse_lynis_log(log_file_path):
    """
    解析lynis.log文件，提取漏洞信息
    """
    vulnerabilities = []
    vuln_id = 0
    
    try:
        with open(log_file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            
        # 分割日志行
        lines = content.split('\n')
        
        current_vuln = None
        
        for line in lines:
            # 查找Suggestion行
            if 'Suggestion:' in line:
                # 提取建议内容
                suggestion_match = re.search(r'Suggestion: (.+?) \[test:([^\]]+)\]', line)
                if suggestion_match:
                    suggestion_text = suggestion_match.group(1).strip()
                    test_id = suggestion_match.group(2).strip()
                    
                    # 查找details和solution
                    details_match = re.search(r'\[details:([^\]]*)\]', line)
                    solution_match = re.search(r'\[solution:([^\]]*)\]', line)
                    
                    details = details_match.group(1).strip() if details_match else ""
                    solution = solution_match.group(1).strip() if solution_match else ""
                    
                    # 创建漏洞条目
                    vuln_name = f"漏洞{vuln_id + 1}"
                    vuln_content = f"测试ID: {test_id}"
                    if details and details != "-":
                        vuln_content += f"详细信息: {details}"
                    
                    # 将建议内容放到loopAction字段
                    vuln_action = suggestion_text
                    
                    vulnerabilities.append({
                        "id": vuln_id,
                        "loopName": vuln_name,
                        "loopContent": vuln_content,
                        "loopAction": vuln_action
                    })
                    vuln_id += 1
            
            # 查找Warning行
            elif 'Warning:' in line:
                warning_match = re.search(r'Warning: (.+?) \[test:([^\]]+)\]', line)
                if warning_match:
                    warning_text = warning_match.group(1).strip()
                    test_id = warning_match.group(2).strip()
                    
                    # 查找details和solution
                    details_match = re.search(r'\[details:([^\]]*)\]', line)
                    solution_match = re.search(r'\[solution:([^\]]*)\]', line)
                    
                    details = details_match.group(1).strip() if details_match else ""
                    solution = solution_match.group(1).strip() if solution_match else ""
                    
                    # 创建漏洞条目
                    vuln_name = f"漏洞{vuln_id + 1}"
                    vuln_content = f"测试ID: {test_id}"
                    if details and details != "-":
                        vuln_content += f"详细信息: {details}"
                    
                    # 将警告内容放到loopAction字段
                    vuln_action = warning_text
                    
                    vulnerabilities.append({
                        "id": vuln_id,
                        "loopName": vuln_name,
                        "loopContent": vuln_content,
                        "loopAction": vuln_action
                    })
                    vuln_id += 1
        
        return vulnerabilities
        
    except FileNotFoundError:
        print(f"错误: 找不到文件 {log_file_path}")
        return []
    except Exception as e:
        print(f"解析文件时出错: {e}")
        return []

def generate_json_output(vulnerabilities):
    """
    生成JSON格式的输出
    """
    output = {
        "data": {
            "loopList": vulnerabilities
        }
    }
    return json.dumps(output, ensure_ascii=False, indent=2)

def main():
    """
    主函数
    """
    log_file = "../2025kylin-development/lynis.log"
    
    print("正在解析lynis.log文件...")
    vulnerabilities = parse_lynis_log(log_file)
    
    if vulnerabilities:
        print(f"找到 {len(vulnerabilities)} 个漏洞/建议")
        print("\n生成的JSON输出:")
        print("=" * 50)
        
        json_output = generate_json_output(vulnerabilities)
        print(json_output)
        
    else:
        print("未找到任何漏洞信息")

if __name__ == "__main__":
    main() 